package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseltemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1) //查询状态为0(新建)或者是1(已分配)的采购单
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();//获取采购单id
        //TODO 确认采购单状态是0或1才可以合并
        List<Long> items = mergeVo.getItems();  //获取采购需求的id
        List<PurchaseDetailEntity> collect1 = items.stream().map(item -> {  //将所有采购需求的信息封装进来
            PurchaseDetailEntity byId = detailService.getById(item);//获取采购需求的id
            return byId;
        }).filter(item -> { //过滤，采购需求的状态为新建或已分配
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        if (collect1.size()!=0) {
            return;
        }
        //判断采购单id如果采购单id为null就新建采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();  //采购单实体类
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode()); //默认采购单的状态
            purchaseEntity.setCreateTime(new Date()); //创建时间默认值
            purchaseEntity.setUpdateTime(new Date()); //修改时间默认值
            this.save(purchaseEntity);  //调用新增方法；
            purchaseId = purchaseEntity.getId();  //获取新建的采购单的id
        }
        //如果采购单id不为null 就合并到该采购单上
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();   //采购需求实体类
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId); //设置采购单的id
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());  //设置状态为已分配状态
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(collect);  //批量修改
        //每次采购单更新  更新修改日期
        PurchaseEntity purchaseEntity = new PurchaseEntity();  //采购单实体类
        purchaseEntity.setId(purchaseId); //设置修改的采购单id
        purchaseEntity.setUpdateTime(new Date());  //设置时间
        this.updateById(purchaseEntity);  //修改
    }

    @Override
    public void received(List<Long> ids) {

        //1.确认当前采购单是新建或已分配状态，才可以被领取
        List<PurchaseEntity> collect = ids.stream().map(id -> {   //将所有采购单的详细信息封装进来
            PurchaseEntity byId = this.getById(id);
            System.out.println(byId);
            return byId;
        }).filter(item -> {
            //过滤，采购单的状态为新建或者已分配
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());  //改变采购单状态，把采购单状态设置为已领取
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变采购单的状态
        this.updateBatchById(collect);  //批量修改
        //3.改变采购需求的状态
        collect.forEach((item)->{   //遍历采购的集合
           List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId()); //按照采购单的id找到采购需求
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();  //采购需求实体类
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());  //改变采购需求的状态为正在采购
                return entity1;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);  //批量修改
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //1.改变采购单状态(如果所有采购项都采购成功状态为完成，如有一个采购项没采购成功状态为有异常)
        Long id = doneVo.getId();
        //2.改变单里采购项的状态
        Boolean flag = true;
        List<PurchaseltemDoneVo> items = doneVo.getItems();//获取所有采购项
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseltemDoneVo item : items) {  //遍历采购项
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());  //采购失败
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());    //采购完成
                //3.将成功采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());//查出当前采购项的详细信息
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);  //批量更新
        //1.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        //3.将成功采购的进行入库
    }

}